package org.dicr.util.data;

import java.util.*;

/**
 * String Utilities
 * 
 * @author Igor A Tarasov &lt;java@dicr.org&gt;
 * @version 060125
 */
public class StringUtils {
	/**
	 * Remove leading and ending spaces and convert empty string to null.
	 */
	public static String normalize(final String str) {
		String s = str;
		if (s != null) {
			s = s.trim();
			if (s.length() < 1) s = null;
		}
		return s;
	}

	/**
	 * Compare to strings with null's possibles.
	 */
	public static boolean compare(final String s1, final String s2) {
		if (s1 == s2) return true;
		if (s1 == null) return s2 == null;
		else if (s2 == null) return false;
		return s1.equals(s2);
	}

	/**
	 * Quote Object.toString() value in \" quotes.
	 */
	public static String quote(final Object val) {
		return "\"" + val + "\"";
	}

	/**
	 * Convert string to zero ended bytes
	 * <P>
	 * If string is null or empty, return empty bytes array.
	 * </P>
	 * 
	 * @param str string to convert
	 * @return bytes of string with zero at the end
	 */
	public static final byte[] toZeroEnded(final String str) {
		byte[] ret = null;
		if (str == null || str.isEmpty()) ret = new byte[1];
		else {
			final byte[] temp = str.getBytes();
			ret = new byte[temp.length + 1];
			System.arraycopy(temp, 0, ret, 0, temp.length);
		}
		ret[ret.length - 1] = 0;
		return ret;
	}

	/**
	 * Convert zero ended bytes to string
	 * <P>
	 * If bytes is null or empty, return empty string. If no zero byte found, construct string from whole bytes array.
	 * </P>
	 * 
	 * @param bytes zero ended bytes
	 * @return string from bytes or null if empty
	 */
	public static final String fromZeroEnded(final byte[] bytes) {
		String ret = null;
		if (bytes != null && bytes.length > 0 && bytes[0] != 0) {
			int pos = 0;
			while (pos < bytes.length && bytes[pos] != 0)
				pos++;
			ret = new String(bytes, 0, pos);
		}
		return ret;
	}
	
	/**
	 * Implode string parts with delimeter
	 * 
	 * @param parts string parts to implode
	 * @param delimeter parts delimeter
	 * @return result string
	 */
	public static final String implode(Collection<String> parts, String delimeter) {
		if (parts == null) throw new IllegalArgumentException("null parts");
		if (parts.isEmpty()) return "";
		if (delimeter == null) throw new IllegalArgumentException("null delimeter");
		StringBuilder sb = new StringBuilder();
		Iterator<String> pi = parts.iterator();
		while (pi.hasNext()) {
			sb.append(pi.next());
			if (pi.hasNext()) sb.append(delimeter);
		}
		return sb.toString();
	}
}
